import {Component, OnInit, AfterViewInit} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import {ElementRef} from '@angular/core';
import {NzModalService} from 'ng-zorro-antd';

import {LoginRegistryService} from '../login-registry.service';

import {UserVo} from '../../../entity/vo/user.vo';

@Component({
  selector: 'app-registry',
  templateUrl: './registry.component.html',
  styleUrls: ['./registry.component.css'],
  providers: [LoginRegistryService]
})
export class RegistryComponent implements OnInit, AfterViewInit {

  validateForm: FormGroup;
  isRegistryBtnLoading = false;

  constructor(private fb: FormBuilder,
              private router: Router,
              private ef: ElementRef,
              private modalService: NzModalService,
              private loginRegistryService: LoginRegistryService) {
  }

  ngOnInit() {
    window.addEventListener('resize', () => {
      this.windowResize();
    });
    this.validateForm = this.fb.group({
      username: [null, [Validators.required]],
      password: [null, [Validators.required]],
      checkPassword: [null, [Validators.required, this.confirmationValidator]],
      nickname: [null, [Validators.required]],
      telPrefix: ['+86'],
      // tel: [null, [Validators.required]],
      // captcha: [null, [Validators.required]],
      agree: [false]
    });
  }

  ngAfterViewInit() {
    this.windowResize();
  }

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.valid) {
      this.isRegistryBtnLoading = true;
      const user = new UserVo();
      user.username = this.validateForm.controls['username'].value;
      user.password = this.validateForm.controls['password'].value;
      user.nickname = this.validateForm.controls['nickname'].value;
      // user.tel = this.validateForm.controls['tel'].value;
      user.tel = '12312312345';
      this.loginRegistryService.registry(user).then(res => {
        this.isRegistryBtnLoading = false;
        switch (res.retcode) {
          case 1:
            this.success({title: '注册成功', content: ''});
            break;
          case -1:
            this.error({title: '注册失败', content: res.msg});
            break;
        }
        console.log(res);
      }).catch(err => {
        this.isRegistryBtnLoading = false;
        this.error({title: '注册失败', content: '网络错误'});
      });
    }
  }

  updateConfirmValidator(): void {
    /** wait for refresh value */
    Promise.resolve().then(() => this.validateForm.controls.checkPassword.updateValueAndValidity());
  }

  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return {required: true};
    } else if (control.value !== this.validateForm.controls.password.value) {
      return {confirm: true, error: true};
    }
  };

  getCaptcha(e: MouseEvent): void {
    e.preventDefault();
  }

  success(res): void {
    this.modalService.success({
      nzTitle: res.title,
      nzContent: res.content,
      nzOkText: '返回登录',
      nzOnOk: () => {
        this.router.navigateByUrl('login');
      },
      nzCancelText: '关闭'
    });
  }

  error(res): void {
    this.modalService.error({
      nzTitle: res.title,
      nzContent: res.content,
      nzOkText: '确定'
    });
  }

  windowResize(): void {
    // 直接操作DOM以防止脏检查
    const containerDom = this.ef.nativeElement.querySelector('.registry-form');
    containerDom.style.marginTop = `-${containerDom.offsetHeight / 2}px`;
  }

}
